package org.zffc.common.handler;


import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.zffc.common.domain.Result;
import org.zffc.common.expection.ZffcBootException;

import java.sql.SQLException;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 基础异常
     */
    @ExceptionHandler(ZffcBootException.class)
    public Result baseException(ZffcBootException e) {
        log.warn("got BaseException:{}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 数据异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result illegalArgumentException(IllegalArgumentException e) {
        log.warn("got IllegalArgumentException:", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(IllegalStateException.class)
    public Result illegalStateException(IllegalStateException e) {
        log.error("got IllegalStateException:", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("系统异常:", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(SQLException.class)
    public Result handleSqlException(Exception e) {
        log.error("系统异常:", e);
        return Result.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Result validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        log.warn(e.getMessage(), e);
        return Result.error(e.getMessage());
    }


    @ExceptionHandler(DataAccessException.class)
    public Result handleDataAccessException(DataAccessException e) {
        log.error("系统异常:", e);
        return Result.error(e.getMessage());
    }
}
